package com.leiy.crawlerjd.task;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.leiy.crawlerjd.pojo.Item;
import com.leiy.crawlerjd.service.ItemService;
import com.leiy.crawlerjd.util.HttpUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Component
public class ItemTask {

    @Autowired
    private HttpUtils httpUtils;

    @Autowired
    private ItemService itemService;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    // 下载任务完成后，间隔多长时间进行下次任务
    @Scheduled(fixedDelay =  100*1000)
    public void itemTask() throws  Exception{
        String url = "https://search.jd.com/Search?keyword=手机&wq=手机&s=56&click=0&page=";
        url = "https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&wq=%E6%89%8B%E6%9C%BA&s=56&click=0&page=";
        // 按照页面分页对手机的搜索结果进行遍历
        for (int i = 1; i < 10; i=i+2) {
            url+=i;
            String html = this.httpUtils.doGetHtml(url);
            this.parse(html);
        }

    }

    // 解析页面，获取商品数据并存储
    private void parse(String html) {
        // 解析html获取document对象
        Document doc = Jsoup.parse(html);

        // 获取spu
        Elements spuEles = doc.select("div#J_goodsList > ul > li");
        for (Element spuEle : spuEles) {
            // System.out.println(spuEle.select("[data-spu]"));
            // spu值
            String spuStr = spuEle.attr("data-spu").trim();
            long spu = spuStr.length() == 0 ? 0 : Long.parseLong(spuEle.attr("data-spu"));
            Elements skuEles = spuEle.select("li.ps-item");
            for (Element skuEle : skuEles) {
                long sku = Long.parseLong(skuEle.select("[data-sku]").attr("data-sku"));
                // System.out.println(sku);
                Item  item = new Item();
                item.setSku(sku);
                List<Item> list = this.itemService.findAll(item);
                if(list.size()>0){
                    continue;
                }
                // 商品集合id
                // spu = spu == 0 ? sku : spu;
                item.setSpu(spu);
                // 商品详情地址
                String itemUrl = "https://item.jd.com/"+sku+".html";
                item.setUrl(itemUrl);

                // 商品图片 浏览器看见的属性值不一定正确，这里的图片就是 data-lazy-img
                String picUrl = "https:" + skuEle.select("img[data-sku]").first().attr("data-lazy-img");
                picUrl = picUrl.replace("/n9/","/n1/");
                String picName = this.httpUtils.doGetImage(picUrl);
                item.setPic(picName);

                // 商品标题 title spuEle.select("div.p-name > a").first().attr("title");
                // String title = spuEle.select("div.p-name > a > em").first().text();
                String itemInfo = this.httpUtils.doGetHtml(item.getUrl()); // 商品详情
                String title = Jsoup.parse(itemInfo).select("div.sku-name").first().text();
                item.setTitle(title);

                // 商品价格   这个价格因该到详情页面获取
                /* String priceUrl =  "https://p.3.cn/prices/mgets?skuIds=J_";
                String priceJson = this.httpUtils.doGetHtml(priceUrl + sku);
                double price = 0;
                try {
                    price = MAPPER.readTree(priceJson).get(0).get("p").asDouble();
                } catch (IOException e) {
                    e.printStackTrace();
                }*/
                String strPrice = Jsoup.parse(itemInfo).select("span.p-price span.price").first().text();
                System.out.println(strPrice);
                double price = 0;
                if(strPrice != null && strPrice.trim().length() >0 ){
                    price = Double.parseDouble(strPrice);
                }else {
                    String priceUrl =  "https://p.3.cn/prices/mgets?skuIds=J_";
                    String priceJson = this.httpUtils.doGetHtml(priceUrl + sku);
                    try {
                        JsonNode p = MAPPER.readTree(priceJson).get(0).get("p");
                        price = p == null ? 0 : p.asDouble() ;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                item.setPrice(price);





                // 创建时间
                item.setCreated(new Date());
                // 更新时间
                item.setUpdated(item.getCreated());
                this.itemService.save(item);
            }

        }
    }


}
